<template>
    <n-scrollbar>
        <n-card style="margin:10px 0;overflow: hidden;height: 100%">
            <FullCalendar ref="calendarRef" :options='calendarOptions'
                          :style="[appStore.sideMode==='menu'?'font-size: 14px':'font-size: 6px']">
            </FullCalendar>
            <n-dropdown
                    placement="bottom-start"
                    trigger="manual"
                    :x="x"
                    :y="y"
                    :options="options"
                    :show="showDropdown"
                    :on-clickoutside="onClickOutside"
                    @select="handleMenuSelect"
            />
            <ScheduleModal v-model:show="modalShow" :data="modalData" @onConfirm="handleConfirm">
            </ScheduleModal>

        </n-card>
    </n-scrollbar>
</template>

<script setup lang="ts">
import FullCalendar from '@fullcalendar/vue3'
import dayGridPlugin from '@fullcalendar/daygrid'
import interactionPlugin from '@fullcalendar/interaction'
import timeGridPlugin from '@fullcalendar/timegrid'
import listPlugin from '@fullcalendar/list';
import zhCN from '@fullcalendar/core/locales/zh-cn'
import {nextTick, onMounted, ref} from "vue";
import ScheduleModal from "@/components/example/modal/ScheduleModal.vue";
import api from "@/api";
import myMoment from "@/utils/common/myMoment";
import bootstrap5Plugin from '@fullcalendar/bootstrap5';
import {getColor} from "@/utils";
import {useAppStore} from "@/sotre";

const appStore = useAppStore()
const props = defineProps({
    disable: {
        type: Boolean,
        default: false
    }
})

const modalShow = ref(false)
const modalData = ref()
const events = ref(new Array<object>())
const calendarRef = ref()
const andParams = ref({})
const orParams = ref({})
const orderParams = ref({})

const options = ref([
    {
        label: '编辑',
        key: '编辑'
    },
    {
        label: '删除',
        key: '删除'
    },])
const showDropdown = ref(false)
const x = ref(0)
const y = ref(0)
const onClickOutside = () => {
    showDropdown.value = false
}
const handleMenuSelect = (key: string | number) => {
    if (key === "编辑") {
        modalShow.value = true
    } else if ("删除") {
        window.$dialog.info({
            title: '是否确定删除？',
            positiveText: '确定',
            negativeText: '取消',
            onPositiveClick: () => {
                api.schedule.remove({
                    id: modalData.value.extendedProps.id
                }).then(res => {
                    if (res && res.data.code === 0) {
                        window.$message.success(res.data.mgs)
                        getList()
                    }
                })
            },
            onNegativeClick: () => {

            },
        })
    }
    onClickOutside()
}


/**
 * 清楚所有事件
 */
const clearEvent = () => {
    let es = calendarRef.value.getApi().getEvents()
    es.forEach((e: { remove: () => void; }) => {
        e.remove()
    })
}
/**
 * 获取日程
 * @param start
 * @param end
 */
const getScheduleList = (start: any, end: any) => {
    clearEvent()
    api.schedule.between({
        start: start,
        end: end,
        pageNo: 1,
        pageSize: 9999,
        andParams: JSON.stringify(andParams),
        orParams: JSON.stringify(orParams),
        orderParams: JSON.stringify(orderParams),
    }).then(res => {
        if (res && res.data.code == 0) {
            let tmp = res.data.data.records
            calendarRef.value.getApi().render()
            Object.keys(tmp).forEach(key => {
                calendarRef.value.getApi().addEvent({
                    title: tmp[key].nurseName,
                    start: tmp[key].start,
                    end: tmp[key].end,
                    color: getColor(tmp[key].jobNum),
                    extendedProps: {
                        username: tmp[key].username,
                        id: tmp[key].id,
                        jobNum: tmp[key].jobNum,
                        nurseName: tmp[key].nurseName,
                        avatar: tmp[key].avatar,
                    }
                })
            })
        }
    })
}
/**
 * 周日程
 */
const getWeekList = () => {
    let curDate = calendarRef.value.getApi().getDate()
    let start = myMoment().week(myMoment(curDate).week() - 1).endOf('week').format("yyyy-MM-DD HH:mm:ss")
    let end = myMoment().week(myMoment(curDate).week()).endOf('week').format("yyyy-MM-DD HH:mm:ss")
    getScheduleList(start, end)
}
/**
 * 月日程
 */
const getMonthList = () => {
    let curDate = calendarRef.value.getApi().getDate()
    let start = myMoment().month(myMoment(curDate).month() - 1).endOf('week').format("yyyy-MM-DD HH:mm:ss")
    let end = myMoment().month(myMoment(curDate).month()).endOf('week').format("yyyy-MM-DD HH:mm:ss")
    getScheduleList(start, end)
}
/**
 * 根据表类型获得日程
 */
const getList = () => {
    if (calendarRef.value.getApi().getCurrentData().currentViewType === 'dayGridMonth') {
        getMonthList()
    } else {
        getWeekList()
    }
}

onMounted(() => {
    getWeekList()
})

/**
 * 选择时间
 * @param info
 */
const handleSelect = (info: any) => {
    modalShow.value = true
    modalData.value = info
    console.log(info)
}
/**
 * 模态框 确认添加
 */
const handleConfirm = () => {
    getList()
}

/**
 * 事件点击
 * @param info
 */
const handleEventClick = (info: any) => {
    if (!props.disable) {
        showDropdown.value = false
        nextTick().then(() => {
            showDropdown.value = true
            x.value = info.jsEvent.clientX
            y.value = info.jsEvent.clientY
        })
        modalData.value = info.event
    }
}
/**
 * 事件拖动
 * @param info
 */
const handleUpdate = (info: any) => {
    let params = {
        ...info.event.extendedProps,
        start: myMoment(info.event.start).format("yyyy-MM-DD HH:mm:ss"),
        end: myMoment(info.event.end).format("yyyy-MM-DD HH:mm:ss")
    }
    updateSchedule(params)
}
/**
 * 更新日程
 * @param params
 */
const updateSchedule = (params: any) => {
    api.schedule.update(params).then(res => {
        if (res && res.data.code === 0) {
            window.$message.success(res.data.msg)
        }
    })
}


const calendarOptions = {
    plugins: [dayGridPlugin, interactionPlugin, timeGridPlugin, listPlugin, bootstrap5Plugin], //插件
    // themeSystem: 'bootstrap5',
    timeZone: 'local',  //时区
    contentHeight: 1000,
    initialView: 'timeGridWeek', //初始视图类型multiMonthYear、timeGridWeek、dayGridWeek、dayGridMonth、listWeek
    headerToolbar: {  //工具栏
        left: 'prev,next,today',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek,listWeek' // user can switch between the two
    },
    eventClick: handleEventClick,  //事件点击
    select: handleSelect, //时间选择
    eventDrop: handleUpdate, //拖动停止
    eventResize: handleUpdate,
    handleWindowResize: true,  //自动视图大小变化
    windowResizeDelay: 1000, //视图变化时间延迟
    selectable: !props.disable,  //是否均可选
    editable: !props.disable,  //是否可编辑
    weekends: true,  //周末是否显示
    locales: [zhCN],  //语言
    locale: 'zh-cn',  //默认
    events: events.value,  //事件
    customButtons: {    //自定义按钮
        prev: {
            click: () => {
                calendarRef.value.getApi().prev()
                getList()
            }
        },
        next: {
            click: () => {
                calendarRef.value.getApi().next()
                getList()
            }
        },
        today: {
            text: '今天',
            click: () => {
                calendarRef.value.getApi().today()
                getList()
            }
        },
        dayGridMonth: {
            text: '月',
            click: () => {
                calendarRef.value.getApi().changeView('dayGridMonth')
                getList()
            }
        }
    }
}


</script>
<style scoped>
:deep(.n-card__content) {
    overflow: hidden;
    height: 100%;
}

</style>
